package com.cykj.pos.service.impl;
import java.util.Date;

import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysDept;
import com.cykj.common.utils.date.DateUtil;
import com.cykj.pos.domain.BizWalletNew;
import com.cykj.pos.domain.vo.BizMerchParentRelated;
import com.cykj.system.domain.BizChannelTwo;
import com.cykj.system.domain.StatisticalMerchant;
import com.cykj.system.mapper.SysUserMapper;
import com.cykj.system.service.ISysDeptService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.annotation.DataSource;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.text.Convert;
import com.cykj.common.enums.DataSourceType;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.posone.PosOneMerchantInfo;
import com.cykj.pos.domain.vo.BizeServerCharge;
import com.cykj.pos.enums.bizstatus.BizStatusContantEnum;
import com.cykj.pos.mapper.BizMerchTransactionsMapper;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.profit.dto.*;
import com.cykj.pos.profit.dto.MerchantDTO;
import com.cykj.pos.profit.dto.MerchantDict;
import com.cykj.pos.service.*;
import com.cykj.pos.test.TestPOJO;
import com.cykj.pos.util.*;
import com.cykj.system.service.ISysDictDataService;
import com.cykj.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报件商户信息Service业务层处理
 *
 * @author ningbingwu
 * @date 2021-01-11
 */
@Service
public class BizMerchantServiceImpl extends ServiceImpl<BizMerchantMapper, BizMerchant> implements IBizMerchantService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBizMerchTransactionsService transRecordsService;

    @Autowired
    private IBizPosMachineService  posMachineService;

    @Autowired
    private IBizMicroInfoService microInfoService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private IBizWalletService walletService;

    @Autowired
    private ISMSService smsService;

    @Autowired
    private IBizMicroInfoService bizMicroInfoService;

    @Autowired
    private IBizMerchTransactionsService bizMerchTransactionsService;

    @Autowired
    private  IBizMerchantService merchantService;

    @Resource
    BizMerchantMapper bizMerchantMapper;

    @Resource
    IBizWalletNewService bizWalletNewService;

    @Autowired
    IBizAreaDictService areaDictService;

    @Autowired
    IBizPosMachineStatusRecordsService iBizPosMachineStatusRecordsService;

    @Resource
    BizMerchTransactionsMapper bizMerchTransactionsMapper;
    @Autowired
    private IBizAgentOpenAccountService iBizAgentOpenAccountService;
    @Autowired
    private IBizUserAccountService bizUserAccountService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public int updataMerchant(BizMerchant bizMerchant) {
        int bizMerchants=bizMerchantMapper.updataMerchant(bizMerchant);
        return bizMerchants;
    }

    @Override
    public BizMerchant getMerchantparentId(Long merchName) {
        return bizMerchantMapper.getMerchantparentId(merchName);
    }
    @Override
    public void generateAllPosMerchParentRelated(){
        bizMerchantMapper.generateAllPosMerchParentRelated();
    }
    @Override
    public String selectMerchId(String userId) {
        String s1=bizMerchantMapper.selectMerchId(userId);
        return s1;
    }
    @Override
    public String selectMerchIdadd(String nickName) {
        String s1=bizMerchantMapper.selectMerchIdadd(nickName);
        return s1;
    }
    @Override
    public int insertMerchant(BizMerchant bizMerchant) {
        int bizMerchants=bizMerchantMapper.insertMerchant(bizMerchant);
        return bizMerchants;
    }
    @Override
    public List<MerchantDTO> queryParentuser() {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId()==1l){
            sysUserman.setUserId(2l);
        }
        List<MerchantDTO> bizMerchants=bizMerchantMapper.queryParentuser(sysUserman.getUserId());
        return bizMerchants;
    }

    @Override
    public List<MerchantDTO> queryParentusers() {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId()==1l){
            sysUserman.setUserId(2l);
        }
        List<MerchantDTO> bizMerchants=bizMerchantMapper.queryParentusers(sysUserman.getUserId());
        return bizMerchants;
    }
    @Override
    public int selectwallet(BizWallet bizWallet) {
        if(bizWallet.getRewardAmount().equals("0")){
            int rows= calculationAamount(bizWallet);
            return rows;
        } else if(bizWallet.getProfitAmount().equals("0")){
            int rows= calculationAamount(bizWallet);
            return rows;
        }else if (!bizWallet.getProfitAmount().equals("0") & !bizWallet.getRewardAmount().equals("0") ){
            int rows= calculationAamount(bizWallet);
            return rows;
        }
        return 1;
    }

    public int calculationAamount(BizWallet bizWallet) {
        // 获得登录人的信息
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*伙伴信息*/
        BizMerchant bizMerchantlists=bizMerchantMapper.selectAtmerchId(bizWallet.getUserId());
        /*钱包信息*/
        BizWallet bizMerchants=bizMerchantMapper.selectwallet(bizWallet.getUserId());
        /*user信息*/
        SysUser sysUser=bizMerchantMapper.selectsysUser(bizWallet.getUserId());
        /*充值奖励的金额*/
        BigDecimal bigrewardAmount=new BigDecimal(bizWallet.getRewardAmount());
        /*结算*/
        BigDecimal bigprofitAmount=new BigDecimal(bizWallet.getProfitAmount());
        /*钱包解密后的奖励金额*/
        String rewardAmounts=DESHelperUtil.decrypt(bizMerchants.getSecretKey(),bizMerchants.getRewardAmount());
        /*钱包解密后的结算金额*/
        String profitAmounts=DESHelperUtil.decrypt(bizMerchants.getSecretKey(),bizMerchants.getProfitAmount());
        /*钱包奖励金额*/
        BigDecimal walletrewardAmount=new BigDecimal(rewardAmounts);
        /*钱包结算金额*/
        BigDecimal walletprofitAmount=new BigDecimal(profitAmounts);
        /*最终的奖励金额*/
        BigDecimal rewardAmount=walletrewardAmount.add(bigrewardAmount);
        /*最终的奖励金额*/
        BigDecimal profitAmount=walletprofitAmount.add(bigprofitAmount);
        /*最终总金额*/
        BigDecimal walletAmount=rewardAmount.add(profitAmount);
        /*结算金额  加密*/
        String finallyprofitAmount=DESHelperUtil.encrypt(bizMerchants.getSecretKey(), String.valueOf(profitAmount));
        /*奖励金额  加密*/
        String finallyrewardAmount=DESHelperUtil.encrypt(bizMerchants.getSecretKey(), String.valueOf(rewardAmount));
        /*最终总金额加密*/
        String finallywalletAmount=DESHelperUtil.encrypt(bizMerchants.getSecretKey(), String.valueOf(walletAmount));
        BizWallet bizMerchartlist=new BizWallet();
        bizMerchartlist.setUserId(bizWallet.getUserId());
        /*结算金额*/
        bizMerchartlist.setProfitAmount(finallyprofitAmount);
        /*奖励金额*/
        bizMerchartlist.setRewardAmount(finallyrewardAmount);
        /*总金额*/
        bizMerchartlist.setWalletAmount(finallywalletAmount);
        /*修改钱包*/
        int rows=bizMerchantMapper.updateTopUp(bizMerchartlist);
        if (rows>0){
            if (bizWallet.getProfitAmount().equals("0")){
                BizMerchBill bizMerchBill1=new BizMerchBill();
                bizMerchBill1.setMerchId(bizMerchantlists.getMerchId());
                bizMerchBill1.setMerchName(bizMerchantlists.getMerchName());
                bizMerchBill1.setBillType("3");
                bizMerchBill1.setAmount(bigrewardAmount);
                bizMerchBill1.setBillDate(format.format(date));
                //添加账单
                bizMerchantMapper.insterbizMerchBill(bizMerchBill1);
                BizTopupBillsDTO bizTopupBillsDTO = new BizTopupBillsDTO();
                bizTopupBillsDTO.setBillMerchId(String.valueOf(bizMerchantlists.getMerchId()));
                bizTopupBillsDTO.setBillNickName(bizMerchantlists.getMerchName());
                bizTopupBillsDTO.setBillTime(bizMerchBill1.getBillDate());
                bizTopupBillsDTO.setBillProfitAmount(bizWallet.getProfitAmount());
                bizTopupBillsDTO.setBillRewardAmount(bizWallet.getRewardAmount());
                bizTopupBillsDTO.setBillPhonenumber(sysUser.getPhonenumber());
                bizTopupBillsDTO.setBillSysUserId(sysUserman.getUserId());
                //添加充值账单
                bizMerchantMapper.insterbizTopupBills(bizTopupBillsDTO);
            }else if (bizWallet.getRewardAmount().equals("0")){
                BizMerchBill bizMerchBill1=new BizMerchBill();
                bizMerchBill1.setMerchId(bizMerchantlists.getMerchId());
                bizMerchBill1.setMerchName(bizMerchantlists.getMerchName());
                bizMerchBill1.setBillType("6");
                bizMerchBill1.setAmount(bigprofitAmount);
                bizMerchBill1.setBillDate(format.format(date));
                //添加账单
                bizMerchantMapper.insterbizMerchBill(bizMerchBill1);
                BizTopupBillsDTO bizTopupBillsDTO = new BizTopupBillsDTO();
                bizTopupBillsDTO.setBillMerchId(String.valueOf(bizMerchantlists.getMerchId()));
                bizTopupBillsDTO.setBillNickName(bizMerchantlists.getMerchName());
                bizTopupBillsDTO.setBillTime(bizMerchBill1.getBillDate());
                bizTopupBillsDTO.setBillProfitAmount(bizWallet.getProfitAmount());
                bizTopupBillsDTO.setBillRewardAmount(bizWallet.getRewardAmount());
                bizTopupBillsDTO.setBillPhonenumber(sysUser.getPhonenumber());
                bizTopupBillsDTO.setBillSysUserId(sysUserman.getUserId());
                //添加充值账单
                bizMerchantMapper.insterbizTopupBills(bizTopupBillsDTO);
            }else if (!bizWallet.getProfitAmount().equals("0") & !bizWallet.getRewardAmount().equals("0")){
                BizMerchBill bizMerchBill1=new BizMerchBill();
                bizMerchBill1.setMerchId(bizMerchantlists.getMerchId());
                bizMerchBill1.setMerchName(bizMerchantlists.getMerchName());
                bizMerchBill1.setBillType("3");
                bizMerchBill1.setAmount(bigrewardAmount);
                bizMerchBill1.setBillDate(format.format(date));
                //添加账单
                bizMerchantMapper.insterbizMerchBill(bizMerchBill1);
                BizMerchBill bizMerchBill2=new BizMerchBill();
                bizMerchBill2.setMerchId(bizMerchantlists.getMerchId());
                bizMerchBill2.setMerchName(bizMerchantlists.getMerchName());
                bizMerchBill2.setBillType("6");
                bizMerchBill2.setAmount(bigprofitAmount);
                bizMerchBill2.setBillDate(format.format(date));
                //添加账单
                bizMerchantMapper.insterbizMerchBill(bizMerchBill2);
                BizTopupBillsDTO bizTopupBillsDTO = new BizTopupBillsDTO();
                bizTopupBillsDTO.setBillMerchId(String.valueOf(bizMerchantlists.getMerchId()));
                bizTopupBillsDTO.setBillNickName(bizMerchantlists.getMerchName());
                bizTopupBillsDTO.setBillTime(bizMerchBill1.getBillDate());
                bizTopupBillsDTO.setBillProfitAmount(bizWallet.getProfitAmount());
                bizTopupBillsDTO.setBillRewardAmount(bizWallet.getRewardAmount());
                bizTopupBillsDTO.setBillPhonenumber(sysUser.getPhonenumber());
                bizTopupBillsDTO.setBillSysUserId(sysUserman.getUserId());
                //添加充值账单
                bizMerchantMapper.insterbizTopupBills(bizTopupBillsDTO);
            }
        }
        return rows;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchant> queryList(BizMerchant bizMerchart) {

        LambdaQueryWrapper<BizMerchant> lqw = Wrappers.lambdaQuery();
        if (bizMerchart.getUserId() != null) {
            lqw.eq(BizMerchant::getUserId, bizMerchart.getUserId());
        }
        if (bizMerchart.getParentId() != null) {
            lqw.eq(BizMerchant::getParentId, bizMerchart.getParentId());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchCode())) {
            lqw.eq(BizMerchant::getMerchCode, bizMerchart.getMerchCode());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchName())) {
            lqw.like(BizMerchant::getMerchName, bizMerchart.getMerchName());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchAbbr())) {
            lqw.eq(BizMerchant::getMerchAbbr, bizMerchart.getMerchAbbr());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchRegion())) {
            lqw.eq(BizMerchant::getMerchRegion, bizMerchart.getMerchRegion());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchAddr())) {
            lqw.eq(BizMerchant::getMerchAddr, bizMerchart.getMerchAddr());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchBizScope())) {
            lqw.eq(BizMerchant::getMerchBizScope, bizMerchart.getMerchBizScope());
        }
        if (StringUtils.isNotBlank(bizMerchart.getMerchType())) {
            lqw.eq(BizMerchant::getMerchType, bizMerchart.getMerchType());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVerifyStatus())) {
            lqw.eq(BizMerchant::getVerifyStatus, bizMerchart.getVerifyStatus());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVerifyResult())) {
            lqw.eq(BizMerchant::getVerifyResult, bizMerchart.getVerifyResult());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVar1())) {
            lqw.eq(BizMerchant::getVar1, bizMerchart.getVar1());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVar2())) {
            lqw.eq(BizMerchant::getVar2, bizMerchart.getVar2());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVar3())) {
            lqw.eq(BizMerchant::getVar3, bizMerchart.getVar3());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVar4())) {
            lqw.eq(BizMerchant::getVar4, bizMerchart.getVar4());
        }
        if (StringUtils.isNotBlank(bizMerchart.getVar5())) {
            lqw.eq(BizMerchant::getVar5, bizMerchart.getVar5());
        }
        return this.list(lqw);
    }

    @Override
    public List<TreeSelect> buildMerchantTreeSelect(List<BizMerchant> merchants) {
        List<BizMerchant> merchantTree = this.buildMerchantTree(merchants);
        return merchantTree.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<BizMerchant> buildMerchantTree(List<BizMerchant> merchants) {
        List<BizMerchant> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (BizMerchant merchant : merchants) {
            tempList.add(merchant.getMerchId());
        }
        for (Iterator<BizMerchant> iterator = merchants.iterator(); iterator.hasNext(); ) {
            BizMerchant merchant = iterator.next();
            if (!tempList.contains(merchant.getMerchId())) {
                recursionFunc(merchants, merchant);
                returnList.add(merchant);
            }
        }

        if (returnList.isEmpty()) return merchants;

        return returnList;
    }

    private void recursionFunc(List<BizMerchant> list, BizMerchant t) {
        List<BizMerchant> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BizMerchant tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFunc(list, tChild);
            }
        }
    }

    private List<BizMerchant> getChildList(List<BizMerchant> list, BizMerchant t) {
        List<BizMerchant> tList = new ArrayList<>();
        Iterator<BizMerchant> it = list.iterator();
        while (it.hasNext()) {
            BizMerchant merchant = it.next();
            Long parentId = merchant.getParentId();
            Long tId = t.getMerchId();
            if (parentId != null && parentId == tId) {
                tList.add(merchant);
            }
        }
        return tList;
    }

    private boolean hasChild(List<BizMerchant> list, BizMerchant t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizMerchant getMerchantByMerchId(Long merId) {
        LambdaQueryWrapper<BizMerchant> merchantQuery = Wrappers.lambdaQuery();
        merchantQuery.eq(BizMerchant::getMerchId, merId);
        BizMerchant merchant = this.getOne(merchantQuery);
        return merchant;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizMerchant getMerchantByUserId(Long loginUser) {
        LambdaQueryWrapper<BizMerchant> merchantQuery = Wrappers.lambdaQuery();
        merchantQuery.eq(BizMerchant::getUserId, loginUser);
        BizMerchant merchant = this.getOne(merchantQuery);
        return merchant;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Long getUserIdByMerchId(Long merchId){
        String sql = "select user_id from biz_merchant where merch_id=? limit 1";
        return jdbcTemplate.queryForObject(sql,new Object[]{merchId},Long.class);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchant> getAllSubNodeAndIncludeSelf(Long merchId) {
        String sql = "SELECT  * FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?))";
        return jdbcTemplate.query(sql, new Object[]{merchId}, new BeanPropertyRowMapper<BizMerchant>(BizMerchant.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchant> getAllSubNodeAndIncludeSelf(Long merchId, BizMerchant merchant) {
        String merchantName = merchant.getMerchName();
        String merchantAbbr = merchant.getMerchAbbr();
        String merchantCode = merchant.getMerchCode();
        String merchantRegion = merchant.getMerchRegion();
        List<Object> paramList = new ArrayList<>();

        StringBuilder sqlBuilder = new StringBuilder("SELECT  * FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?)) ");

        paramList.add(merchId);

        if (StringUtils.isNotBlank(merchantName)) {
            paramList.add("%" + merchantName + "%");
            sqlBuilder.append(" and merch_name like ? ");
        }
        if (StringUtils.isNotBlank(merchantAbbr)) {
            paramList.add("%" + merchantAbbr + "%");
            sqlBuilder.append(" and merch_abbr like ? ");
        }
        if (StringUtils.isNotBlank(merchantCode)) {
            paramList.add(merchantCode);
            sqlBuilder.append(" and merch_code=? ");
        }
        if (StringUtils.isNotBlank(merchantRegion)) {
            paramList.add(merchantRegion);
            sqlBuilder.append(" and merch_region=? ");
        }
        Object[] params = paramList.toArray();

        return jdbcTemplate.query(sqlBuilder.toString(), params, new BeanPropertyRowMapper<BizMerchant>(BizMerchant.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthlyNewMerchantCounts(Long merchId) {
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).substring(0, 7);
        String sql = "SELECT  count(*) FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?)) and create_time like ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{merchId, formatedDate}, Integer.class);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthLyNewMerchantExcludeChild(Long merchId) {
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).substring(0, 7);
        String sql = "SELECT  merch_id FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?)) and create_time like ?";
        List<Long> merchIds = jdbcTemplate.queryForList(sql, new Object[]{merchId, formatedDate}, Long.class);
        String queryLeafNode = "select count(1) from biz_merchant where parent_id=? and create_time like ?";
        Integer leafCounts = 0;
        for (Long merchantId : merchIds) {
            Integer count = jdbcTemplate.queryForObject(queryLeafNode, new Object[]{merchantId, formatedDate}, Integer.class);
            if (count < 1) {
                leafCounts++;
            } else {
                continue;
            }
        }
        return leafCounts;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
    public String generateMerchCode(String prefix){
        Integer seqNo = this.getGenerateSequence(prefix);
        String suffixCode =  String.format("%09d", seqNo);
        String certificationNo = prefix + suffixCode;
        return certificationNo;
    }
    @Override
    @Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
    public String generateMerchCode(String prefix,String regionCode){
        Integer seqNo = this.getGenerateSequence(prefix);
        String suffixCode =  String.format("%09d", seqNo);
        String certificationNo = prefix + regionCode + suffixCode;
        return certificationNo;
    }
    private  Integer  getGenerateSequence(String seqName){
        Integer param2Value = (Integer) jdbcTemplate.execute(
                new CallableStatementCreator() {
                    public CallableStatement createCallableStatement(Connection con) throws SQLException {
                        String storedProc = "{call generateSequence(?,?)}";// 调用的sql
                        CallableStatement cs = con.prepareCall(storedProc);
                        cs.setString(1, seqName);// 设置输入参数的值
                        cs.registerOutParameter(2, Types.INTEGER);// 注册输出参数的类型
                        return cs;
                    }
                }, new CallableStatementCallback() {
                    public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                        cs.execute();
                        return cs.getInt(2);// 获取输出参数的值
                    }
                });
        return param2Value;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<MerchantDict> getChildMerchartDictList(Long parentId){
        MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setUserId(parentId);
        List<BizMerchant> merchants = this.getChildMerchantList(merchantDTO,-1,-1);
        List<MerchantDict> dicts = new ArrayList<>(merchants.size());
        for(int i=0;i< merchants.size();i++){
            Long userId = merchants.get(i).getUserId();
            SysUser user = sysUserService.selectUserById(userId);

            MerchantDict dict = new MerchantDict();
            dict.setId(i);
            dict.setDictValue(merchants.get(i).getMerchId());
            dict.setDictLabel(merchants.get(i).getMerchName());
            dict.setUserId(userId);
            dict.setMobile(user.getPhonenumber());
            // 添加头像
            dict.setPortrait(user.getPortrait());
            dicts.add(dict);
        }
        return dicts;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchant> getChildMerchantList(MerchantDTO merchantDTO,int pageNo,int pageSize){
        BizMerchant parentMerchant = this.getMerchantByUserId(merchantDTO.getUserId());
        Long parentUserId = parentMerchant.getUserId();
        LambdaQueryWrapper<BizMerchant> merchantQuery = Wrappers.lambdaQuery();
        BizMerchant merchant = this.getMerchantByUserId(parentUserId);
        merchantQuery.eq(BizMerchant::getParentId ,merchant.getMerchId());
        String nickName = merchantDTO.getNickName();
        String verifyStatus = merchantDTO.getVerifyStatus();
        if(StringUtils.isNotBlank(nickName)){
            merchantQuery.likeRight(BizMerchant::getMerchName,nickName);
        }
        /*if(StringUtils.isNotBlank(verifyStatus)){
            merchantQuery.eq(BizMerchant::getVerifyStatus,verifyStatus);
        }*/
        if(pageNo == -1 || pageSize == -1) return this.list(merchantQuery);
        merchantQuery.last("LIMIT "+(pageNo -1)*pageSize+","+pageSize);
        return this.list(merchantQuery);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getChildMerchantCounts(Long userId,String verifyStatus,String thisMonth,String nickName){
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setUserId(userId);
        sysUserDTO.setNickName(nickName);
        return bizMerchantMapper.getChildMerchantCounts(sysUserDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public  PartnerDTO getPartnerDetail(Long userId){
        String today = DateUtils.Date2String(new Date(),"yyyy-MM-dd");
        String thisDate = DateUtils.getCaculateYearAndMonth("","yyyy-MM");
        String lastDate = DateUtils.getCaculateYearAndMonth("last","yyyy-MM");
        BizMerchant merchant = this.getMerchantByUserId(userId);
        Long merchId = merchant.getMerchId();
        PartnerDTO partnerDTO = new PartnerDTO();
        partnerDTO.setMerchId(merchId);
        partnerDTO.setUserId(userId);
        partnerDTO.setThisDate(thisDate);
        partnerDTO.setLastDate(lastDate);
        partnerDTO.setToday(today);
        partnerDTO = bizMerchantMapper.selectPartnerDetail(partnerDTO);
        return partnerDTO;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<PartnerDTO> getPagedPartnerList(MerchantDTO merchantDTO){
        List<PartnerDTO> partners = new ArrayList<>();
        int pageNo = merchantDTO.getPageNo();
        int pageSize = merchantDTO.getPageSize();
        // List<BizMerchant> merchants2 = this.getChildMerchantList(merchantDTO,pageNo,pageSize);
        int start = (pageNo -1)*pageSize ;
        merchantDTO.setStart(start);
        List<MerchantVO> merchants = bizMerchantMapper.getChildMerchantList(merchantDTO);
        for(MerchantVO merchant:merchants){
            // 当前月
            String thisDate = DateUtils.getCaculateYearAndMonth("","yyyy-MM");
            PartnerDTO partnerDTO = new PartnerDTO();
            partnerDTO.setThisDate(thisDate);
            partnerDTO.setMerchId(merchant.getMerchId());
            if(merchant.getMerchId()==null){// 商户id为null 代表该伙伴没有实名认证
                partnerDTO.setPartnerMobile(merchant.getPhonenumber());
                partnerDTO.setPortrait(merchant.getPortrait());
                partnerDTO.setTeamTransAmount(new BigDecimal(0));
            }else{
                partnerDTO = bizMerchantMapper.getPagedPartnerDataInfo(partnerDTO);
                //刷卡和扫码的费率邦的Id
                List<PartnerDTO> rateList = bizMerchantMapper.findRate(merchant.getUserId());
                for (PartnerDTO rate : rateList) {
                    //刷卡费率
                    partnerDTO.setRateT0(bizMerchantMapper.findRateDetail(rate.getRateT0()));
                    //扫码费率
                    partnerDTO.setQrsettleRate(bizMerchantMapper.findRateDetail(rate.getQrsettleRate()));
                }
            }
            partners.add(partnerDTO);
        }
        // 排序  1 升序   2 降序
        Collections.sort(partners, new Comparator<PartnerDTO>() {
            @Override
            public int compare(PartnerDTO o1, PartnerDTO o2) {
                if(merchantDTO.getSortTime()==1){//升序
                    return o1.getTeamTransAmount().compareTo(o2.getTeamTransAmount());
                }else{
                    return o2.getTeamTransAmount().compareTo(o1.getTeamTransAmount());
                }
            }
        });
        return partners;
    }

    @Override
    @Transactional
    public void microMerchantRegister(MicroMerchantDTO microMerchantDTO){
        Long userId = microMerchantDTO.getUserId();

        SysUser user = sysUserService.selectUserById(userId);
        Long inviteUserId = user.getInviteUserId();

        BizMerchant parentMerchant = this.getMerchantByUserId(inviteUserId);

        //商户入驻过则更新，未入驻过则新增
        BizMerchant merchant = this.getMerchantByUserId(userId);
        if(merchant == null){
            merchant = new BizMerchant();
        }

        merchant.setParentId(parentMerchant.getMerchId());
        merchant.setUserId(userId);
        merchant.setMerchCode(this.generateMerchCode("ZF"));

        merchant.setMerchName(microMerchantDTO.getMerchName());
        merchant.setMerchType(microMerchantDTO.getMerchType());

        String scope = microMerchantDTO.getMerchBizScope();
        merchant.setMerchBizScope(StringUtils.isNotBlank(scope)?scope:"");

        String abbr = microMerchantDTO.getMerchAbbr();
        merchant.setMerchAbbr(StringUtils.isNotBlank(abbr)?abbr:"");

        String addr = microMerchantDTO.getMerchAddr();
        merchant.setMerchAddr(StringUtils.isNotBlank(addr)?addr:"");

        //省市区县编码
        String proviceCode = microMerchantDTO.getMerchProvince();
        String cityCode = microMerchantDTO.getMerchCity();
        String countyCode = microMerchantDTO.getMerchCounty();

        merchant.setVar1(StringUtils.isNotBlank(proviceCode)?proviceCode:"");
        merchant.setVar2(StringUtils.isNotBlank(cityCode)?cityCode:"");
        merchant.setVar3(StringUtils.isNotBlank(countyCode)?countyCode:"");
        String provinceName = "";
        if(StringUtils.isNotBlank(proviceCode)){
            provinceName = areaDictService.getById(Integer.parseInt(proviceCode)).getCname();
        }
        String cityName = "";
        if(StringUtils.isNotBlank(cityCode)){
            cityName = areaDictService.getById(Integer.parseInt(cityCode)).getCname();
        }
        String countyName = "";
        if(StringUtils.isNotBlank(countyCode)){
            countyName = areaDictService.getById(Integer.parseInt(countyCode)).getCname();
        }
        if(StringUtils.isNotBlank(provinceName) || StringUtils.isNotBlank(cityName) || StringUtils.isNotBlank(countyName)){
            merchant.setMerchRegion(provinceName+cityName+countyName);
        }

        // 新增关联提现模板
        System.out.println("withdrawalId"+user.getWithdrawalId());
        WithdrawalRateTemplate withdrawalRateTemplate = bizMerchantMapper.getWithdrawalData(String.valueOf(user.getWithdrawalId()));
        merchant.setWithdrawalRate(withdrawalRateTemplate.getProfitRate());
        merchant.setWithdrawalFee(withdrawalRateTemplate.getProfitFee());
        merchant.setRewardWithdrawalRate(withdrawalRateTemplate.getRewardRate());
        merchant.setRewardWithdrawalFee(withdrawalRateTemplate.getRewardFee());
        merchant.setWithdrawalId(user.getWithdrawalId());
        Boolean success = this.saveOrUpdate(merchant);
        if(!success) return;

        Long merchId = merchant.getMerchId();

        if(merchId == null) return;

        BizMicroInfo microInfo = bizMicroInfoService.getBizMicroInfoByMerchId(merchId);
        if(microInfo == null){
            microInfo = new BizMicroInfo();
        }

        microInfo.setMerchId(merchId);

        microInfo.setMerchBank(microMerchantDTO.getMerchBank());
        microInfo.setMerchBankCard(microMerchantDTO.getMerchBankCard());
        microInfo.setMerchBankCardno(microMerchantDTO.getMerchBankCardno());

        //省市编码
        String bankProvinceCode = microMerchantDTO.getMerchProvince();
        String bankCityCode = microMerchantDTO.getMerchBankCity();

        //扩展字段存编码
        microInfo.setVar1(bankProvinceCode);
        microInfo.setVar2(bankCityCode);
        //存省市汉字
        microInfo.setMerchBankCity(provinceName+cityName);

        microInfo.setMerchBankMobile(microMerchantDTO.getMerchBankMobile());
        microInfo.setMerchIdcard(microMerchantDTO.getMerchIdcard());
        microInfo.setMerchIdcardName(microMerchantDTO.getMerchIdcardName());

        String duedata = microMerchantDTO.getMerchIdcardDuedate();
        microInfo.setMerchIdcardDuedate(StringUtils.isNotBlank(duedata)?duedata:"");

        microInfo.setMerchIdcardPositive(microMerchantDTO.getMerchIdcardPositive());
        microInfo.setMerchIdcardBack(microMerchantDTO.getMerchIdcardBack());

        String idcardHand = microMerchantDTO.getMerchIdcardHand();
        microInfo.setMerchIdcardHand(StringUtils.isNotBlank(idcardHand)?idcardHand:"");

        microInfoService.saveOrUpdate(microInfo);

        user.setNickName(microMerchantDTO.getMerchIdcardName());
        sysUserService.updateUserProfile(user);
        // 插入商户和上级商户的对应关系信息 biz_merch_parent_related
        //更新钱包的user_name
        bizWalletNewService.updateWalletUserNameByUserId(userId,user.getNickName());
        // merchId
        merchantService.generateMerchParentRelated(merchId);
    }

    @Override
    @Transactional
    public BizStatusContantEnum partnerRegister(PartnerInviteDTO partnerInviteDTO){
        String invitorCode = partnerInviteDTO.getInvitorUserId();
        if(!StringUtils.isNotBlank(invitorCode)) return BizStatusContantEnum.PARTNER_IS_NULL;
        String loginAccount = partnerInviteDTO.getMobile();
        if(!StringUtils.isNotBlank(loginAccount)) return BizStatusContantEnum.MOBILE_IS_NULL;

        String password = partnerInviteDTO.getPassword();
        if(!StringUtils.isNotBlank(password)) return BizStatusContantEnum.PASSWORD_IS_NULL;
//      String password = VerifyCodeUtils.getVerifyCode();
        //邀请人是否存在
        LambdaQueryWrapper<BizMerchant> lqw = Wrappers.lambdaQuery();
        lqw.eq(BizMerchant::getMerchCode, invitorCode);
        BizMerchant merchant = this.getOne(lqw);
        SysUser inviteUser = sysUserService.selectUserById(merchant.getUserId());
        if(inviteUser == null){
            return BizStatusContantEnum.PARTNER_REGISTER_INVITOR_ISNOTEXIST;
        }
        //判断是否已注册
        SysUser user = sysUserService.selectUserByUserName(loginAccount);
        if(user != null){
            return BizStatusContantEnum.PARTNER_REGISTER_FINISHED;
        }
        /*邀请人的所在部门*/
       Long deptIdParent=iBizAgentOpenAccountService.selectDeptId(invitorCode);
        SysUser partnerUser = new SysUser();
        partnerUser.setUserName(loginAccount);
        //TODO：这里还需要加一层密码密文解密功能，即前端传输过来的是密码密文（加密算法协商解决），解密后保存到本地数据库
        partnerUser.setPassword(SecurityUtils.encryptPassword(password));
        partnerUser.setInviteUserId(inviteUser.getUserId());
        partnerUser.setRoleIds(new Long[]{2L});//默认角色-普通角色
        partnerUser.setPhonenumber(loginAccount);
        partnerUser.setDeptId(deptIdParent);//默认部门-合作伙伴
        partnerUser.setStatus("0");//伙伴默认启用
        partnerUser.setCreateBy(String.valueOf(inviteUser.getUserId()));
        partnerUser.setSuffix(inviteUser.getSuffix());
        partnerUser.setWithdrawalId(partnerInviteDTO.getWithdrawalId());
        int counts = sysUserService.insertUser(partnerUser,partnerInviteDTO.getVerifyCode());
        if(1 == counts){
            // 生成一个钱包
            SysDept sysDept = sysDeptService.selectDeptById(deptIdParent);
            BizWalletNew bizWalletNew = new BizWalletNew() ;
            bizWalletNew.setDeptId(deptIdParent);
            bizWalletNew.setDeptName(sysDept.getDeptName());

            // 扣款钱包
            AizDeductionWallet aizDeductionWallet = new AizDeductionWallet();
            aizDeductionWallet.setDeptId(deptIdParent);
            aizDeductionWallet.setDeptName(sysDept.getDeptName());
            aizDeductionWallet.setUserId(partnerUser.getUserId());
            aizDeductionWallet.setCreateTime(DateUtil.getBaiDuTime());
            bizWalletNewService.insertDeductionWallet(aizDeductionWallet);
            //伙伴注册成功后接口会自动将伙伴用户主键返回，利用该主键即可同时给新伙伴创建我的钱包账户
            StatisticalMerchant aizStatisticalMerchant = new StatisticalMerchant();
            List<BizChannelTwo> bizChannel = sysUserService.selectChannel();
            bizChannel.stream().forEach(e->{
                //  代理钱包
                bizWalletNew.setChannelId(e.getChannelId());
                bizWalletNew.setChannelName(e.getChannelName());
                bizWalletNew.setCreateTime(DateUtil.getBaiDuTime());
                bizWalletNew.setUserId(partnerUser.getUserId());
                bizWalletNewService.save(bizWalletNew);
                aizStatisticalMerchant.setChannelId(e.getChannelId().intValue());
                aizStatisticalMerchant.setChannelName(e.getChannelName());
                aizStatisticalMerchant.setUserId(partnerUser.getUserId());
                userMapper.insertStatistical(aizStatisticalMerchant);

                // 提现分润钱包钱包
                AizWithdrawalWallet aizWithdrawalWallet = new AizWithdrawalWallet();
                aizWithdrawalWallet.setDeptId(deptIdParent);
                aizWithdrawalWallet.setDeptName(sysDept.getDeptName());
                aizWithdrawalWallet.setUserId(partnerUser.getUserId());
                aizWithdrawalWallet.setChannelId(e.getChannelId());
                aizWithdrawalWallet.setChannelName(e.getChannelName());
                aizWithdrawalWallet.setCreateTime(DateUtil.getBaiDuTime());
                aizWithdrawalWallet.setAmount(BigDecimal.ZERO);
                bizWalletNewService.insertWithdrawalWallet(aizWithdrawalWallet);

            });


            return BizStatusContantEnum.PARTNER_REGISTER_SUCCESS;
        }
        return BizStatusContantEnum.PARTNER_REGISTER_FAIL;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BankCardDTO getBankCardInfo(BankCardDTO bankCardDTO){
        BizMerchant merchant = this.getMerchantByUserId(bankCardDTO.getUserId());
        BizMicroInfo micro = microInfoService.getBizMicroInfoByMerchId(merchant.getMerchId());
        bankCardDTO.setIdCardName(micro.getMerchIdcardName());
        bankCardDTO.setIdCard(micro.getMerchIdcard());
        bankCardDTO.setBankCardNo(micro.getMerchBankCardno());
        bankCardDTO.setBankName(micro.getMerchBank());
        bankCardDTO.setBankCity(micro.getMerchBankCity());
        bankCardDTO.setBankReservedMobile(micro.getMerchBankMobile());
        // 银行卡照片url
        bankCardDTO.setBankCardImg(micro.getMerchBankCard());
        return bankCardDTO;
    }

    @Override
    @Transactional
    public BankCardDTO alterBankCardInfo(BankCardDTO bankCardDTO){
        BizMerchant merchant = this.getMerchantByUserId(bankCardDTO.getUserId());
        BizMicroInfo micro = microInfoService.getBizMicroInfoByMerchId(merchant.getMerchId());

        micro.setMerchIdcardName(bankCardDTO.getIdCardName());
        micro.setMerchIdcard(bankCardDTO.getIdCard());
        micro.setMerchBankCardno(bankCardDTO.getBankCardNo());
        micro.setMerchBank(bankCardDTO.getBankName());
        micro.setMerchBankCity(bankCardDTO.getBankCity());
//        micro.setMerchBankMobile(bankCardDTO.getBankReservedMobile());
        // 银行卡照片
        micro.setMerchBankCard(bankCardDTO.getBankCardImg());

        microInfoService.saveOrUpdate(micro);

        return bankCardDTO;
    }

    @Override
    @Transactional
    public void addMerchantTransaction(BizMerchTransDTO merchTransDTO) {
        BizMerchTransactions merchTransaction = new BizMerchTransactions();
        // ------------------------快钱支付接口提供字段-----------------------------
        merchTransaction.setTradeType(merchTransDTO.getTradeType()); // 交易类型
        merchTransaction.setBankAuthCode(merchTransDTO.getAuthCode()); // 银行授权码
        merchTransaction.setServiceEntryMode(merchTransDTO.getServiceEntryMode()); //输入模式
        merchTransaction.setReceiptType(merchTransDTO.getReceiptType()); // 产品类型
        merchTransaction.setStatus(merchTransDTO.getStatus());  // 交易状态
        merchTransaction.setDiscountRateFlag(merchTransDTO.getDiscountRateFlag());  // 优惠汇率
        merchTransaction.setIdTxn(merchTransDTO.getIdTxn()); // 交易编号
        merchTransaction.setErrorMsg(merchTransDTO.getErrorMsg()); // 错误信息
        merchTransaction.setCardType(merchTransDTO.getCardType()); // 卡类型
        merchTransaction.setSecondOrgId(merchTransDTO.getSecondOrgID()); // 二级机构号
        merchTransaction.setPhoneNo(merchTransDTO.getPhoneNo()); // 手机号
        merchTransaction.setTransAmount(Convert.toBigDecimal(merchTransDTO.getAmt())); // 交易金额
        //merchTransaction.setTransAmount(new BigDecimal(merchTransDTO.getAmt()));
        merchTransaction.setDeviceType(merchTransDTO.getDeviceType()); // 设备类型
        merchTransaction.setErrorCode(merchTransDTO.getErrorCode()); // 错误码
        merchTransaction.setPosCode(merchTransDTO.getSnCode());// 设备sn号
        merchTransaction.setUserName(merchTransDTO.getUserName()); // 商户实名姓名
        merchTransaction.setMerchFlagCode(merchTransDTO.getMerchantId());// 商户标识
        merchTransaction.setDirectlyOrgId(merchTransDTO.getDirectlyOrgID()); // 直属机构号
        merchTransaction.setOrderId(merchTransDTO.getOrderId()); // 外部订单号
        merchTransaction.setTransDate(merchTransDTO.getTxnTime());// 交易时间
        // -------------------------------------------------------------------------
        // -----------------------------未来可开发字段-------------------------------
        merchTransaction.setProductCode(merchTransDTO.getProductCode()); // 产品码
        merchTransaction.setIsStoreCashier(merchTransDTO.getIsStoreCachier()); // 店面收银交易标识
        merchTransaction.setS0PackageFlag(merchTransDTO.getS0PackageFlag()); //S0手续费套餐生效标识
        merchTransaction.setSpecialMode(merchTransDTO.getSpecialMode()); // 一机双模标识
        merchTransaction.setEsimFlag(merchTransDTO.getEsimFlg()); //e-sim卡服务费标识
        merchTransaction.setIdCardNo(merchTransDTO.getIdCardNo()); //用户实名身份证号
        merchTransaction.setAuthMerchantId(merchTransDTO.getAuthMerchantId()); //授权商户编号
        merchTransaction.setAuthTerminalId(merchTransDTO.getAuthTerminalId()); //授权终端编号
        merchTransaction.setTransactionStatus("1"); // 消费交易
        // 保存到数据库即可
        bizMerchTransactionsService.saveOrUpdate(merchTransaction);
    }

    @Override
    @Transactional
    public void cancelMerchantTransaction(BizCancelTransDTO merchTransDTO) {
        BizMerchTransactions merchTransaction = new BizMerchTransactions();
        // ------------------------快钱支付接口提供字段-----------------------------
        BigDecimal transAmount = Convert.toBigDecimal(merchTransDTO.getAmt());
        merchTransaction.setTransAmount(transAmount.negate());//值变为负值  -600.00
        merchTransaction.setOriginOutTraceNo(merchTransDTO.getOriginOutTraceNo()); // 原交易外部订单号
        merchTransaction.setIdTxn(merchTransDTO.getIdTxn()); // 交易编号
        merchTransaction.setMerchFlagCode(merchTransDTO.getMerchantId());  //商户标识
        merchTransaction.setOrderId(merchTransDTO.getOutTraceNo()); //外部订单号
        merchTransaction.setTransDate(merchTransDTO.getTxnTime()); //交易请求时间
        // -------------------------------------------------------------------------
        // -----------------------------未来可开发字段-------------------------------
        merchTransaction.setSecondOrgId(merchTransDTO.getSecondOrgID()); //二级机构号
        merchTransaction.setDirectlyOrgId(merchTransDTO.getDirectlyOrgID()); //直属机构号
        merchTransaction.setTransactionStatus("2"); // 撤销交易
        // 保存撤销记录信息
        bizMerchTransactionsService.saveOrUpdate(merchTransaction);
    }

    @Override
    @Transactional
    public void returnMerchantTransaction(BizReturnTransDTO merchTransDTO) {
        BizMerchTransactions merchTransaction = new BizMerchTransactions();
        // ------------------------快钱支付接口提供字段-----------------------------
        BigDecimal transAmount = Convert.toBigDecimal(merchTransDTO.getAmt());
        merchTransaction.setTransAmount(transAmount.negate());//值变为负值  -600.00
        merchTransaction.setOriginOutTraceNo(merchTransDTO.getOriginOutTraceNo()); // 原交易外部订单号
        merchTransaction.setIdTxn(merchTransDTO.getIdTxn()); // 交易编号
        merchTransaction.setMerchFlagCode(merchTransDTO.getMerchantId());  //商户标识
        merchTransaction.setOrderId(merchTransDTO.getOutTraceNo()); //外部订单号
        merchTransaction.setTransDate(merchTransDTO.getTxnTime()); //交易请求时间
        // -------------------------------------------------------------------------
        // -----------------------------未来可开发字段-------------------------------
        merchTransaction.setSecondOrgId(merchTransDTO.getSecondOrgID()); //二级机构号
        merchTransaction.setDirectlyOrgId(merchTransDTO.getDirectlyOrgID()); //直属机构号
        merchTransaction.setTransactionStatus("3"); // 退货交易
        // 保存撤销记录信息
        bizMerchTransactionsService.saveOrUpdate(merchTransaction);
    }

    /**
     * 商户下没有孩子得商户  就是我们需要的商户
     *
     * @param merchId
     * @return
     */
    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthlyTotalMerchantByMerId(Long merchId) {
        // 拿到商户下的所有商户和合作伙伴
        String sql = "SELECT  merch_id FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?))";
        List<Long> merchIds = jdbcTemplate.queryForList(sql, new Object[]{merchId}, Long.class);
        // 获得商户下的所有子商户
        String queryLeafNode = "select count(1) from biz_merchant where parent_id=?";
        Integer leafCounts = 0;
        for (Long merchantId : merchIds) {
            Integer count = jdbcTemplate.queryForObject(queryLeafNode, new Object[]{merchantId}, Integer.class);
            // 如果没有子节点  那么就说明是普通商户  散户
            if (count < 1) {
                leafCounts++;
            } else {
                continue;
            }
        }
        return leafCounts;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthlyMyMerchantCounts(Long merchId) {
        // 拿到自己的孩子
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).substring(0, 7);
        String sql = "SELECT  merch_id FROM biz_merchant WHERE parent_id=? and create_time like ?";
        List<Long> merchIds = jdbcTemplate.queryForList(sql, new Object[]{merchId, formatedDate}, Long.class);
        // 获得孩子的孩子
        String queryLeafNode = "select count(1) from biz_merchant where parent_id=? and create_time like ?";
        Integer leafCounts = 0;
        for (Long merchantId : merchIds) {
            Integer count = jdbcTemplate.queryForObject(queryLeafNode, new Object[]{merchantId, formatedDate}, Integer.class);
            if (count < 1) {
                leafCounts++;
            } else {
                continue;
            }
        }
        return leafCounts;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getTtotalMerchAndPartnerCounts(Long merchId) {
        String sql = "SELECT  count(*) FROM biz_merchant WHERE FIND_IN_SET(merch_id,findMerchSubNode(?))";
        return jdbcTemplate.queryForObject(sql, new Object[]{merchId}, Integer.class)-1;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<MerchantDict> selectPagedPartnerList(MerchantDTO merchantDTO) {
        Integer pageNo = merchantDTO.getPageNo();
        Integer pageSize = merchantDTO.getPageSize();
        if(pageNo !=null && !"".equals(pageNo) && pageSize!=null && !"".equals(pageSize)){
            Integer start = (merchantDTO.getPageNo()-1)*merchantDTO.getPageSize();
            // 页的开始值
            merchantDTO.setStart(start);
        }
        return bizMerchantMapper.selectPagedPartnerList(merchantDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthlyNewPartnerCount(Long merchId) {
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).substring(0, 7);
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        return bizMerchantMapper.getMonthlyNewPartnerCount(homePageDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getMonthlyNewMerchCounts(Long merchId) {
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).substring(0, 7);
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        return bizMerchantMapper.getMonthlyNewMerchCounts(homePageDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getTotalNewMerchCounts(Long merchantId) {
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchantId);
        return bizMerchantMapper.getMonthlyNewMerchCounts(homePageDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getActivePostMachineCounts(Long merchantId, String month) {
        // 设置一下月
        String formatedDate = DateUtils.getCaculateYearAndMonth(month,"yyyy-MM");
        if(month==null || "".equals(month)){
            formatedDate = null;
        }
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchantId);
        homePageDTO.setYearMonth(formatedDate);
        return bizMerchantMapper.getMonthlyNewMerchCounts(homePageDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getTotalMerchantByMerId(Long merchId) {
        String sql = "SELECT COUNT(*) FROM biz_pos_machine_status_records r "
                +"WHERE r.records_type='2' AND r.sn_code IN "+
                "(SELECT pos_code FROM biz_pos_machine WHERE merch_id=?)";
        return jdbcTemplate.queryForObject(sql, new Object[]{merchId}, Integer.class);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizMerchant> getParentMerchByUserId(Long userId) {
        return bizMerchantMapper.selectParentMerchByUserId(userId);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public HomePageDataDTO getHomePageDataDTO(Long merchId,Long userId) {
        String formatedDate = DateUtils.getCaculateYearAndMonth("","yyyy-MM");
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        return bizMerchantMapper.selectHomePageDataDTO(homePageDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public TransAmountDataDTO getTransAmountDataDTO(Long merchId, Long userId) {
        String formatedDate = DateUtils.getCaculateYearAndMonth("this","yyyy-MM");
        HomePageDTO homePageDTO = new HomePageDTO();
        homePageDTO.setMerchId(merchId);
        homePageDTO.setYearMonth(formatedDate);
        homePageDTO.setUserId(userId);
        TransAmountDataDTO transAmountDataDTO = bizMerchantMapper.selectTransAmountDataDTO(homePageDTO);
        // 计算一下伙伴业绩   总业绩-个人业绩
        transAmountDataDTO.setPartnerTransAmount(transAmountDataDTO.getMonthlyTransAmount().subtract(transAmountDataDTO.getMerchantTransAmount()));
        return transAmountDataDTO;
    }


    @Override
    public List<MerchantDict> selectPagedPartnerListAll(MerchantDTO merchantDTO) {
        Integer pageNo = merchantDTO.getPageNo();
        Integer pageSize = merchantDTO.getPageSize();
        if(pageNo !=null && !"".equals(pageNo) && pageSize!=null && !"".equals(pageSize)){
            Integer start = (merchantDTO.getPageNo()-1)*merchantDTO.getPageSize();
            // 页的开始值
            merchantDTO.setStart(start);
        }
        return bizMerchantMapper.selectPagedPartnerListAll(merchantDTO);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<PartnerDetailDTO> getPartnerAmountStatistical(MerchantDTO merchantDTO) {
        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        BigDecimal bigDecimal = new BigDecimal("0");
        BizMerchant merchant = this.getMerchantByUserId(merchantDTO.getUserId());
        merchantDTO.setMerchId(merchant.getMerchId());// 存入merch_id
        Date date = new Date();// 当前时间
        if (merchantDTO.getSignAmount()==1){// 交易额按一周查
            // 先写出一周的时间
            for (int i=0;i<7;i++){
                String time = DateUtils.dateSubOne(date,-i);// 循环查出一周时间
                merchantDTO.setMonthType(time);// 把时间条件存进去
                PartnerDetailDTO partnerDetailDTO = bizMerchantMapper.getPartnerAmountStatistical(merchantDTO);
                if (partnerDetailDTO==null){
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setMoney(bigDecimal);
                    String cutOutTime = DateUtils.cutOutDate(time,1);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO1);
                }
                if (partnerDetailDTO!=null){
                    String cutOutTime = DateUtils.cutOutDate(time,1);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        if (merchantDTO.getSignAmount()==2){// 交易额按半年查
            // 先查出半年的时间
            for (int i=0;i<6;i++){
                String time = DateUtils.dateSubMonth(date,-i);
                merchantDTO.setMonthType(time);
                PartnerDetailDTO partnerDetailDTO = bizMerchantMapper.getPartnerAmountStatistical(merchantDTO);
                if (partnerDetailDTO==null){
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setMoney(bigDecimal);
                    String cutOutTime = DateUtils.cutOutMonth(time,2);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO1);
                }
                if (partnerDetailDTO!=null){
                    String cutOutTime = DateUtils.cutOutMonth(time,2);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        return null;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<PartnerDetailDTO> getPartnerMachinesStatistical(MerchantDTO merchantDTO) {
        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        BigDecimal bigDecimal = new BigDecimal("0");
        BizMerchant merchant = this.getMerchantByUserId(merchantDTO.getUserId());
        merchantDTO.setMerchId(merchant.getMerchId());// 存入merch_id
        Date date = new Date();// 当前时间
        if (merchantDTO.getSignActiveMachines()==1){// 激活数按一周查
            // 先写出一周的时间
            for (int i=0;i<7;i++){
                String time = DateUtils.dateSubOne(date,-i);// 循环查出一周时间
                merchantDTO.setMonthType(time);// 把时间条件存进去
                PartnerDetailDTO partnerDetailDTO = bizMerchantMapper.getPartnerMachinesStatistical(merchantDTO);
                if (partnerDetailDTO==null){
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setNum(0);
                    String cutOutTime = DateUtils.cutOutDate(time,1);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO1);
                }
                if (partnerDetailDTO!=null){
                    String cutOutTime = DateUtils.cutOutDate(time,1);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        if (merchantDTO.getSignActiveMachines()==2){// 激活数按半年查
            // 先查出半年的时间
            for (int i=0;i<6;i++){
                String time = DateUtils.dateSubMonth(date,-i);
                merchantDTO.setMonthType(time);
                PartnerDetailDTO partnerDetailDTO = bizMerchantMapper.getPartnerMachinesStatistical(merchantDTO);
                if (partnerDetailDTO==null){
                    PartnerDetailDTO partnerDetailDTO1 = new PartnerDetailDTO();
                    partnerDetailDTO1.setNum(0);
                    String cutOutTime = DateUtils.cutOutMonth(time,2);
                    partnerDetailDTO1.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO1);
                }
                if (partnerDetailDTO!=null){
                    String cutOutTime = DateUtils.cutOutMonth(time,2);
                    partnerDetailDTO.setTime(cutOutTime);
                    list.add(i,partnerDetailDTO);
                }
            }
            Collections.reverse(list);
            return list;
        }
        return null;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizMerchant getMerchantByParentId(Long parentId) {
        LambdaQueryWrapper<BizMerchant> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BizMerchant::getMerchId,parentId);
        BizMerchant bizMerchant = this.getOne(wrapper);
        return bizMerchant;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public SysUser getSuperior(Long userId) {
        SysUser sysUser = bizMerchantMapper.getSuperior(userId);
        return sysUser;
    }

    @Override
    @Transactional
    public void generateMerchParentRelated(Long merchId) {
        bizMerchantMapper.generateMerchParentRelated(merchId);
    }



    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizPosMachineStatusRecords selectBizPosMachineStatusRecords(String snCode) {
        BizPosMachineStatusRecords b = iBizPosMachineStatusRecordsService.selectBizPosMachineStatusRecords(snCode);
        return b;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<MerchantInfoDTO> queryMerchantInfo(MerchantDTO merchantDTO) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = dateFormat.format(date).substring(0,7);
        /*merchantDTO.setMonthType(nowDate);*/
        // 产生问题：查询此商户当月的交易记录 可能没有记录 但是此商户存在 用时间筛选会把商户过滤掉
        // 我没弄明白sql 所以选用了两个sql语句来实现此问题
        // 第一个 只查询商户信息 不进行查询商户的交易
        List<MerchantInfoDTO> list = bizMerchantMapper.queryMerchantInfo(merchantDTO);
        // 第二个 查询当月的交易金额
        for (int i=0;i<list.size();i++){
            list.get(i).setQueryMonth(nowDate);
            MerchantInfoDTO amount =  bizMerchantMapper.queryMerchantAmount(list.get(i));
            list.get(i).setTransAmount(amount.getTransAmount());
        }
        return list;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<MerchantInfoDTO> queryOrderlyMerchantInfo(MerchantDTO merchantDTO) {
        // 存入当月信息
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = dateFormat.format(date).substring(0,7);
        /*merchantDTO.setMonthType(nowDate);*/
        if(merchantDTO.getPageNo()!=null && merchantDTO.getPageSize()!=null){
            Integer pageNo = merchantDTO.getPageNo();
            Integer pageSize = merchantDTO.getPageSize();
            Integer start = (pageNo-1)*pageSize;
            merchantDTO.setStart(start);
        }
        List<MerchantInfoDTO> list = bizMerchantMapper.queryOrderlyMerchantInfo(merchantDTO);
        for (int i=0;i<list.size();i++){
            list.get(i).setQueryMonth(nowDate);
            MerchantInfoDTO amount =  bizMerchantMapper.queryMerchantAmount(list.get(i));
            list.get(i).setTransAmount(amount.getTransAmount());
        }
        List<MerchantInfoDTO> listOver = new ArrayList<MerchantInfoDTO>();
        if (merchantDTO.getOrderly()==1){
            listOver = ListUtils.searchAsc(list);
        } else if (merchantDTO.getOrderly()==2){
            listOver = ListUtils.searchDes(list);
        }
        return listOver;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public MerchantInfoDTO queryMerchantEquipmentInfo(String id) {
        MerchantInfoDTO merchantInfoDTO = bizMerchantMapper.queryMerchantEquipmentInfo(id);
        return merchantInfoDTO;
    }

    @Override
    public void updateTerminalNo(String snCode, String terminalNo) {
        bizMerchantMapper.updateTerminalNo(snCode, terminalNo);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public HomePageDataDTO getHomePageDataDTOInfo(SysUserDTO userVo) {
        HomePageDataDTO info=bizMerchantMapper.selectHomePageDataDTOInfo(userVo);
        return info;
    }

    @Override
    public List<RankingDTO> queryPartnerRankingByTime(RankingDTO rankingDTO) {
        Date date = new Date();
        List<RankingDTO> list = new ArrayList<RankingDTO>();
        List<RankingDTO> finalList = new ArrayList<RankingDTO>();
        if (rankingDTO.getIdent().equals("1")){
            // 查询昨天的
            String yesterday = DateUtils.dateSubOne(date,-1);
            MerchantDTO merchantDTO = new MerchantDTO();
            merchantDTO.setMonthType(yesterday);
            list = bizMerchantMapper.queryPartnerRankingByTime(merchantDTO);
            // 现在要加上特殊的 假数据 去数据库去查表
            int a = list.size();
            List<BizSpecialRanking> list1 = bizMerchantMapper.querySpecialRankingByTime(merchantDTO);
            for (BizSpecialRanking bizSpecialRanking : list1){// 把这些假数据 加进去
                RankingDTO fakeRank = new RankingDTO();
                fakeRank.setActivateNum(bizSpecialRanking.getActivateNum());// 激活数
                fakeRank.setHeadPortrait(bizSpecialRanking.getHeadPortrait());// 头像
                fakeRank.setNickNAme(bizSpecialRanking.getRankName());// 姓名
                fakeRank.setIdent("1");// 昨天的
                list.add(a,fakeRank);// 存入list中
                a++;
            }
            // 再把list排序
            // 方式2: 升序排列
            Collections.sort(list, new Comparator<RankingDTO>() {
                @Override
                public int compare(RankingDTO o1, RankingDTO o2) {
                    if ((o1.getActivateNum() > o2.getActivateNum())){
                        return -1;
                    }
                    if (o1.getActivateNum() == o2.getActivateNum()){
                        return 0;
                    }
                    return 1;
                }
            });
            // 截取十位
            if (list.size()>10){
                finalList = list.subList(0,10);// 截取十个
            }else {
                finalList = list;
            }
        }else if (rankingDTO.getIdent().equals("2")){
            // 按本月查询
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
            MerchantDTO merchantDTO = new MerchantDTO();
            merchantDTO.setMonthType(sf.format(date));
            list = bizMerchantMapper.queryPartnerRankingByTime(merchantDTO);
            // 现在要加上特殊的 假数据 去数据库去查表
            int a = list.size();
            List<BizSpecialRanking> list1 = bizMerchantMapper.querySpecialRankingByMonth(merchantDTO);
            for (BizSpecialRanking bizSpecialRanking : list1){// 把这些假数据 加进去
                RankingDTO fakeRank = new RankingDTO();
                fakeRank.setActivateNum(bizSpecialRanking.getActivateNum());// 激活数
                fakeRank.setHeadPortrait(bizSpecialRanking.getHeadPortrait());// 头像
                fakeRank.setNickNAme(bizSpecialRanking.getRankName());// 姓名
                fakeRank.setIdent("1");// 昨天的
                list.add(a,fakeRank);// 存入list中
                a++;
            }
            // 再把list排序
            // 方式1: 降序排列
            Collections.sort(list, new Comparator<RankingDTO>() {
                @Override
                public int compare(RankingDTO o1, RankingDTO o2) {
                    if ((o1.getActivateNum() > o2.getActivateNum())){
                        return -1;
                    }
                    if (o1.getActivateNum() == o2.getActivateNum()){
                        return 0;
                    }
                    return 1;
                }
            });
            // 截取十位
            if (list.size()>10){
                finalList = list.subList(0,10);// 截取十个
            }else {
                finalList = list;
            }
        }
        return finalList;
    }

    @Override
    public TestPOJO queryAllParent(BizMerchant bizMerchant) {
        TestPOJO testPOJO = new TestPOJO();
        testPOJO.setMySelf(bizMerchant.getMerchName());
        for (int i=1;i>0;i++){
            String a = "";
            String b = "";
            // 先去查上级
            BizMerchant bizMerchant1 = bizMerchantMapper.queryAllParent(bizMerchant);
            if (bizMerchant1!=null && i==1){
                a = bizMerchant.getMerchName();
                b = bizMerchant1.getMerchName() + "/" + a;
                testPOJO.setParentName(b);
            }
            if (bizMerchant1!=null && i>1){
                a = bizMerchant1.getMerchName();
                b = a + "/" + testPOJO.getParentName();
                testPOJO.setParentName(b);
            }
            if (bizMerchant1==null)
                break;
            bizMerchant.setParentId(bizMerchant1.getParentId());
            bizMerchant.setMerchName(bizMerchant1.getMerchName());
        }
        return testPOJO;
    }

    @Override
    public List<BizMerchant> queryListUi(BizMerchant bizMerchant) {
        List<BizMerchant> queryListUi=bizMerchantMapper.queryListUi(bizMerchant);
        return queryListUi;
    }


    @Override
    @Transactional
    public int updateByIdVue(BizMerchant bizMerchart) {
        int i=bizMerchantMapper.updateByIdVue(bizMerchart);//修改merchantId 伙伴转移
        BizMerchant newMerchent=bizMerchantMapper.selectById(bizMerchart.getParentId());//查询新上级的userid
        Long newUserId=newMerchent.getUserId();
        int u=bizMerchantMapper.updateByUserId(newUserId,bizMerchart.getUserId());//把要调整的伙伴'邀请人'改为新伙伴的userid
        if(i==1 && u==1){
            // 运行函数（商户和上级商户的对应关系信息 biz_merch_parent_related）
            bizMerchantMapper.generateAllMerchParentRelated();
            return i;
        }else {
            return 0;
        }

    }

    @Transactional
    public int updateRelativeById(BizMerchant bizMerchart){
        int i=bizMerchantMapper.updateByIdVue(bizMerchart);//修改merchantId 伙伴转移
        BizMerchant newMerchent=bizMerchantMapper.selectById(bizMerchart.getParentId());//查询新上级的userid
        Long newUserId=newMerchent.getUserId();
        int u=bizMerchantMapper.updateByUserId(newUserId,bizMerchart.getUserId());//把要调整的伙伴'邀请人'改为新伙伴的userid
        return u+i;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizMerchant getMerchantByName(String merchName) {
        LambdaQueryWrapper<BizMerchant> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BizMerchant :: getMerchName,merchName);
        BizMerchant bizMerchant = this.getOne(wrapper);
        return bizMerchant;
    }

    @Override
    public List<com.cykj.pos.domain.dto.MerchantDTO> personList() {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        List<com.cykj.pos.domain.dto.MerchantDTO> list = new ArrayList<>();
//        if (sysUserman.getUserId()==1l){
//            sysUserman.setUserId(2l);
            com.cykj.pos.domain.dto.MerchantDTO dto = new com.cykj.pos.domain.dto.MerchantDTO();
            dto.setMerchId(2l);
            dto.setNickName("服务中心");
            dto.setUserName("99999999");
            list.add(dto);
//        }else{
//            list= bizMerchantMapper.personList(sysUserman.getUserId());
//        }
//        List<com.cykj.pos.domain.dto.MerchantDTO> list= bizMerchantMapper.personList(sysUserman.getUserId());
        return list;
    }

    @Override
    public List<com.cykj.pos.domain.dto.MerchantDTO> getALlMerchant() {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        if (sysUserman.getUserId()==1l){
            sysUserman.setUserId(2l);
        }
        List<com.cykj.pos.domain.dto.MerchantDTO> list= bizMerchantMapper.personList(sysUserman.getUserId());
        return list;
    }

    @Override
    public boolean addMerchantTransactionBySft(ShengFuTongTradeDTO shengFuTongTradeDTO) {
        String jsonExtData = shengFuTongTradeDTO.getExtData();
        BizMerchTransactions merchTransaction = new BizMerchTransactions();
        merchTransaction.setServiceEntryMode(shengFuTongTradeDTO.getTxnType());//交易类型
        int amt=Integer.parseInt(shengFuTongTradeDTO.getAmt());
        double d=amt/100;
        String getAmt = d+"";
        merchTransaction.setTransAmount(new BigDecimal(getAmt));//交易金额
        merchTransaction.setAuthMerchantId(shengFuTongTradeDTO.getMerchantId());//POS商户号
        merchTransaction.setAuthTerminalId(shengFuTongTradeDTO.getTerminalId());//终端号
        merchTransaction.setOrderId(shengFuTongTradeDTO.getOrderId());//盛付通订单号
        try {
            merchTransaction.setTransDate(DateUtils.getTime(shengFuTongTradeDTO.getTxnTime()));//交易时间
        } catch (Exception e) {
            e.printStackTrace();
        }
        merchTransaction.setIdTxn(shengFuTongTradeDTO.getTxnRef());//交易参考号
        merchTransaction.setErrorCode(shengFuTongTradeDTO.getRespCode());//交易应答码,00交易成功;其他失败
        List<String> list =new ArrayList();
        list.add("");
        if(shengFuTongTradeDTO.getRespCode().equals("00")){
            merchTransaction.setErrorMsg("交易成功");
        }else if(shengFuTongTradeDTO.getRespCode().equals("01")){
            merchTransaction.setErrorMsg("pos机交易失败，请联系发卡行查发卡行或检查卡内余额");
        }else if(shengFuTongTradeDTO.getRespCode().equals("02")){
            merchTransaction.setErrorMsg("pos机交易失败，请联系发卡行查发卡行或检查卡内余额");
        }else if(shengFuTongTradeDTO.getRespCode().equals("03")){
            merchTransaction.setErrorMsg("商户未登记，无权使用银联pos机终端联系银行卡服务中心处理");
        }else if(shengFuTongTradeDTO.getRespCode().equals("04")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行操作员没收卡（这种情况为高风险卡片，有黑卡或仿卡的嫌疑）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("05")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行发卡不予承兑，与发银行联系查询");
        }else if(shengFuTongTradeDTO.getRespCode().equals("06")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行发卡行故障，稍等重新刷卡");
        }else if(shengFuTongTradeDTO.getRespCode().equals("07")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行特殊条件下没收卡，这种情况为高风险卡片，有黑卡或仿卡的嫌疑");
        }else if(shengFuTongTradeDTO.getRespCode().equals("09")){
            merchTransaction.setErrorMsg("交易失败，请重试重做该交易，稍等重新刷卡");
        }else if(shengFuTongTradeDTO.getRespCode().equals("12")){
            merchTransaction.setErrorMsg("交易失败，请重试发卡行不支持的交易，这种情况为部分银行卡不识别银联pos机上的刷卡器或未和银联签订支付清算协议，或者商户未签到（注意：也有可能是我司内部配置问题，或者银联投诉关闭终端，客服同事可联系运营同事询问）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("13")){
            merchTransaction.setErrorMsg("交易金额超限，请重试交易金额无效，采用小金额交易或与发卡行联系，可向银行申请暂时提升信誉额度，或小额刷卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("14")){
            merchTransaction.setErrorMsg("无效卡号，请联系发卡行无效卡号，与银行卡服务中心或发卡行联系，长时间未使用或未交年费管理费情况造成，或者注销卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("15")){
            merchTransaction.setErrorMsg("此卡不能受理与银行卡服务中心联系处理，未接入银联网络，银联不予以清算和结账。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("19")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行刷卡读取数据有误，重新刷卡");
        }else if(shengFuTongTradeDTO.getRespCode().equals("20")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行与银行卡服务中心或发卡行联系");
        }else if(shengFuTongTradeDTO.getRespCode().equals("21")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行与银行卡服务中心或发卡行联系");
        }else if(shengFuTongTradeDTO.getRespCode().equals("22")){
            merchTransaction.setErrorMsg("操作有误，请重试 POS状态与中心不符，重新签到，确定操作员号码和密码正确，重新刷卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("23")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行不可接受的交易费，这笔交易资金存在风险或者未签订银联协议");
        }else if(shengFuTongTradeDTO.getRespCode().equals("25")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行发卡行未能找到有关记录，核对有关资料重做该交易或与发卡行联系");
        }else if(shengFuTongTradeDTO.getRespCode().equals("30")){
            merchTransaction.setErrorMsg("交易失败，请重试检查卡磁条是否完好或反方向刷卡或者银联pos机的磁条没有问题，以及其他接口正常。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("31")){
            merchTransaction.setErrorMsg("此卡不能受理此发卡方未与中心开通业务，检查此卡是否是签订银联协议的银行卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("33")){
            merchTransaction.setErrorMsg("过期卡，请联系发卡行过期的卡或与发卡行联系，暂时冻结结算功能");
        }else if(shengFuTongTradeDTO.getRespCode().equals("34")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行有作弊嫌疑的卡，操作员可以没收（黑卡仿卡，高风险卡）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("35")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行有作弊嫌疑的卡，操作员可以没收（黑卡仿卡，高风险卡）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("36")){
            merchTransaction.setErrorMsg("此卡有误，请换卡重试有作弊嫌疑的卡，操作员可以没收（黑卡仿卡，高风险卡）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("37")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行有作弊嫌疑的卡，操作员可以没收（黑卡仿卡，高风险卡）");
        }else if(shengFuTongTradeDTO.getRespCode().equals("38")){
            merchTransaction.setErrorMsg("密码错误次数超限密码输错的次数超限，一般pos机结算刷卡为保护持卡人利益，连续输入3次未能输入正确，发卡行系统自动冻结此卡，24小时后自动解冻。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("39")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行可能刷卡操作有误，请重新刷卡");
        }else if(shengFuTongTradeDTO.getRespCode().equals("40")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行发卡行不支持的交易类型，查看卡内余额以及操作流程得当，重新刷卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("41")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行挂失的卡，与发卡行联系处理，此卡已经挂失，一般为盗卡，高风险卡。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("42")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡方发卡行找不到此帐户，此卡为黑卡，防范风险。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("43")){
            merchTransaction.setErrorMsg("没收卡，请联系收单行被窃卡，操作员可以没收，黑卡、盗卡防范风险");
        }else if(shengFuTongTradeDTO.getRespCode().equals("44")){
            merchTransaction.setErrorMsg("交易失败，请联系发卡行可能刷卡操作有误，重新刷卡，确定刷卡流程和步骤正确。");
        }else if(shengFuTongTradeDTO.getRespCode().equals("48")){
            merchTransaction.setErrorMsg("该卡片未激活，请持卡人确认近期是否有换过卡，使用的是否是旧卡");
        }else if(shengFuTongTradeDTO.getRespCode().equals("58")){
            merchTransaction.setErrorMsg("不支持的交易");
        }else if(shengFuTongTradeDTO.getRespCode().equals("63")){
            merchTransaction.setErrorMsg("校验签名失败");
        }else if(shengFuTongTradeDTO.getRespCode().equals("96")){
            merchTransaction.setErrorMsg("系统异常");
        }else if(shengFuTongTradeDTO.getRespCode().equals("P0")){
            merchTransaction.setErrorMsg("处理中");
        }else {
            merchTransaction.setErrorMsg("交易失败");
        }
        merchTransaction.setIdCardNo(shengFuTongTradeDTO.getShortPan());//卡号末4位

        if (com.cykj.common.utils.StringUtils.isNotBlank(jsonExtData) && jsonExtData.startsWith("{") && jsonExtData.endsWith("}"))  {
            //转json对象
            JSONObject json = JSON.parseObject(jsonExtData);
            //判断卡类型
            if(json.getString("cardType").equals("CC") || json.getString("cardType").equals("SCC")){
                merchTransaction.setCardType("0001");//信用卡
                merchTransaction.setDiscountRateFlag("0");//发卡机构  扫码支付
            }else if(json.getString("cardType").equals("DC")){
                merchTransaction.setCardType("0002");//借记卡/储蓄卡
                merchTransaction.setDiscountRateFlag("0");//发卡机构  扫码支付
            }else if(json.getString("cardType").equals("OA")){
                merchTransaction.setCardType("0003");//扫码
                merchTransaction.setDiscountRateFlag("");//发卡机构  扫码支付
            }else if(json.getString("orderType").equals("3")){
                merchTransaction.setCardType("0003");//扫码
                merchTransaction.setDiscountRateFlag("");//发卡机构  扫码支付
            }



            merchTransaction.setPosCode(json.getString("sn"));//sn号
            merchTransaction.setMerchFlagCode(json.getString("sdpMerchant"));//盛付通商户号
            merchTransaction.setUserName(json.getString("merchantName"));//商户名称
            merchTransaction.setPhoneNo(json.getString("ss"));//SIM卡上印的那4排数字
            merchTransaction.setDeviceType(json.getString("clientOSType"));//终端类型
        }
        // 保存到数据库即可
        int i=bizMerchTransactionsMapper.saveBySftTransaction(merchTransaction);
        if(i==1){
            return true;
        }
        return false;
    }

    @Override
    public List<PosOneMerchantInfo> getPosOneMerchantInfo(MerchantDTO merchantDTO) {
        return null;
    }

    @Override
    public void modifyRate(ModifyRateDTO modifyRateDTO) {
        bizMerchantMapper.modifyRate(modifyRateDTO);
    }

    @Override
    public BizMerchant selectBizMerchantBySN(String snCode) {
        return bizMerchantMapper.selectBizMerchantBySN(snCode);
    }

    @Override
    public void updataMerchantStatus(String snCode) {
        bizMerchantMapper.updataMerchantStatus(snCode);
    }

    @Override
    public void generateAllPosMerchantRelatedProcedure() {
        bizMerchantMapper.generateAllPosMerchantRelatedProcedure();
    }

    @Override
    public BizMerchantReturnMoney selectBizServiceCharge(Long userId) {
        return bizMerchantMapper.selectBizServiceCharge(userId);
    }

    @Override
    public List<BizeServerCharge> echoServerBizServiceCharge() {
        return bizMerchantMapper.echoServerBizServiceCharge();
    }

    @Override
    public void updataserverRate(ModifyRateDTO modifyRateDTO) {
        bizMerchantMapper.updataserverRate(modifyRateDTO);
    }

    @Override
    public Long selectServerId(Long userId) {
        return bizMerchantMapper.selectServerId(userId);
    }

    @Override
    public ModifyRateDTO echoRate(ModifyRateDTO modifyRateDTO) {
        return bizMerchantMapper.echoRate(modifyRateDTO);
    }

    @Override
    public List<BizOrganization> selectBizOrganization(String outmer) {
        return bizMerchantMapper.selectBizOrganization(outmer);
    }

    @Override
    public BizMerchantReceiver selectBizMerchantReceiver(BizMerchant bizMerchant) {
        return bizMerchantMapper.selectBizMerchantReceiver(bizMerchant);
    }

    @Override
    public BizMerchantReceiver selectBizMerchantReceiverTypeB(BizMerchant bizMerchant) {
        return bizMerchantMapper.selectBizMerchantReceiverTypeB(bizMerchant);
    }

    @Override
    public List<BizTransactionAmountEntity> getSomeData() {
        return bizMerchantMapper.getSomeData();
    }

    @Override
    public void saveBackMerchant(String merchantCode) {
        bizMerchantMapper.saveBackMerchant(merchantCode);
    }

    @Override
    public List<BizWallet> getCdList(BizWallet bizWallet) {
        List<BizWallet> list=new ArrayList<>();
        BizWallet vo=new BizWallet();
        //查询本级沉淀金额
        BizWallet wallet=bizMerchantMapper.selectwallet(bizWallet.getUserId());
        //查询下级沉淀金额
        List<BizWallet> subWalletlist=bizMerchantMapper.selectsubwallet(bizWallet.getUserId());
        //解密本级
        String profitAmount= DESHelperUtil.decrypt(wallet.getSecretKey(), wallet.getProfitAmount());//结算
        String rewardAmount= DESHelperUtil.decrypt(wallet.getSecretKey(), wallet.getRewardAmount());//奖励
        String walletAmount= DESHelperUtil.decrypt(wallet.getSecretKey(), wallet.getWalletAmount());//总
        //解密下级并累加
        BigDecimal sumProfitAmount=new BigDecimal("0.00");
        BigDecimal sumRewardAmount=new BigDecimal("0.00");
        BigDecimal sumWalletAmount=new BigDecimal("0.00");
        for (BizWallet walletvo:subWalletlist) {
            String subProfitAmount= DESHelperUtil.decrypt(walletvo.getSecretKey(), walletvo.getProfitAmount());//结算
            String subRewardAmount= DESHelperUtil.decrypt(walletvo.getSecretKey(), walletvo.getRewardAmount());//奖励
            String subWalletAmount= DESHelperUtil.decrypt(walletvo.getSecretKey(), walletvo.getWalletAmount());//总
            sumProfitAmount=sumProfitAmount.add(new BigDecimal(subProfitAmount));
            sumRewardAmount=sumRewardAmount.add(new BigDecimal(subRewardAmount));
            sumWalletAmount=sumWalletAmount.add(new BigDecimal(subWalletAmount));
        }
        //封装参数--本级
        vo.setRewardAmount(rewardAmount);
        vo.setProfitAmount(profitAmount);
        vo.setWalletAmount(walletAmount);
        //封装参数--下级
        vo.setVar1(sumProfitAmount.toString());
        vo.setVar2(sumRewardAmount.toString());
        vo.setVar3(sumWalletAmount.toString());
        vo.setVar4(sumWalletAmount.add(new BigDecimal(walletAmount)).toString());
        list.add(vo);
        return list;
    }

    @Override
    public List<BizMerchParentRelated> getMerchantListByMerchId(Long merchId) {
        List<BizMerchParentRelated> list = bizMerchantMapper.getMerchantListByMerchId(merchId);
        return list;
    }

    @Override
    public AjaxResult withdrawalInterval(BizMerchant bizMerchant) {
        bizMerchant = bizMerchantMapper.getWithdrawalInterval(bizMerchant.getUserId());
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        if(bizMerchant != null){
            map.put("withdrawalRate1",BigDecimal.ZERO);
            map.put("withdrawalRate2",bizMerchant.getWithdrawalRate());
            map.put("withdrawalFee1",BigDecimal.ZERO);
            map.put("withdrawalFee2",bizMerchant.getWithdrawalFee());
            map.put("rewardWithdrawalRate1",BigDecimal.ZERO);
            map.put("rewardWithdrawalRate2",bizMerchant.getRewardWithdrawalRate());
            map.put("rewardWithdrawalFee1",BigDecimal.ZERO);
            map.put("rewardWithdrawalFee2",bizMerchant.getRewardWithdrawalFee());
            return AjaxResult.success("提现政策区间",map);
        }else{
            return AjaxResult.error("此代理未设置区间");
        }
    }

    @Override
    public List<Long> getMerchantByNameLike(String merchName) {
        return bizMerchantMapper.getMerchantByNameLike(merchName);
    }

    @Override
    public List<BizMerchant> getAllMerchants() {
        return bizMerchantMapper.getAllMerchants();
    }

    @Override
    public List<BizMerchant> executeMerchList(BizMerchant bizMerchant) {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        bizMerchant.setDeptId(sysUserman.getDeptId().toString());
        List<BizMerchant> merchantList = bizMerchantMapper.selectAllMerchList(bizMerchant);
        return merchantList;
    }

    @Override
    public List<com.cykj.pos.domain.dto.MerchantDTO> getPersonList() {
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        List<com.cykj.pos.domain.dto.MerchantDTO> list = new ArrayList<>();
        if (sysUserman.getUserId()==1l){
            sysUserman.setUserId(2l);
            list= bizMerchantMapper.personList(sysUserman.getUserId());
        }else{
            list= bizMerchantMapper.personList(sysUserman.getUserId());
        }
        return list;
    }

    @Override
    public List<BizWalletNew> queryWalletDetail(BizMerchant bizMerchant) {
        List<BizWalletNew> list = bizMerchantMapper.queryWalletDetail(bizMerchant);
        return list;
    }
}
